package cn.jlearn.proxy.agent.handler.bs;

import cn.jlearn.proxy.agent.AgentStartApp;
import cn.jlearn.proxy.agent.container.ForwardClient;
import cn.jlearn.proxy.agent.container.TcpForwardClient;
import cn.jlearn.proxy.common.body.TcpTunnelBody;
import cn.jlearn.proxy.common.container.SwitchContainer;
import cn.jlearn.proxy.common.enums.ProtocolEnum;
import cn.jlearn.proxy.common.handler.AbstractBsHandler;
import cn.jlearn.proxy.common.packet.BsPacket;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;


/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/5/12 4:45 下午
 */
public class TcpTunnelOpenReqHandler extends AbstractBsHandler<TcpTunnelBody> {

    @Override
    public Class<TcpTunnelBody> bodyClass() {
        return TcpTunnelBody.class;
    }

    @Override
    public void handler(BsPacket packet, TcpTunnelBody bsBody, ChannelContext channelContext) throws Exception {
        String bsId = bsBody.getBsId();
        ChannelContext cc = null;
        SwitchContainer container;
        if (ProtocolEnum.HTTP.getCode().equals(bsBody.getProtocol())) {
            if (ForwardClient.clientTioConfig != null) {
                cc = Tio.getByBsId(ForwardClient.clientTioConfig, bsId);
            }
            container = new ForwardClient(AgentStartApp.TARGET_HOST, AgentStartApp.TARGET_PORT, bsId);
        } else {
            if (TcpForwardClient.clientTioConfig != null) {
                cc = Tio.getByBsId(TcpForwardClient.clientTioConfig, bsId);
            }
            container = new TcpForwardClient(AgentStartApp.TARGET_HOST, AgentStartApp.TARGET_PORT, bsId);
        }
        if (cc == null) {
            container.start();
        }
    }

}
